<?php

namespace App\Models\System;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;

class SystemNoticesModel extends BaseModel
{
    use KfSoftDeletes;
    protected $table = 'system_notices';
    protected $dates = ['isDeleted'];

    const QUESTION_NOTICE = 1;  //问卷调查  特殊的

    protected $fillable = [
        'updatedByUid',
        'isDeleted',
        'updatedAt',
        'title',
        'content',
        'type',
        'startTime',
        'endTime',
        'presenceArea',
        'createdAt',
        'createdByUid',
        'createdAt',
    ];

    protected $appends = [
        'status',
        'typeText',
        'presenceAreaText',
    ];

    //公告状态
    const STATUS_NOT_STARTED = 0;
    const STATUS_CONDUCT     = 1;
    const STATUS_END         = 2;

    const STATUS_MAPPING = [
        self::STATUS_NOT_STARTED => '未开始',
        self::STATUS_CONDUCT     => '进行中',
        self::STATUS_END         => '已结束',
    ];

    //公告类型
    const NOTICE_TYPE_TEXT     = 0;
    const NOTICE_TYPE_QUESTION = 1;
    const NOTICE_TYPE_IMAGE      = 2;

    const NOTICE_MAPPING = [
        self::NOTICE_TYPE_TEXT     => '文字公告',
        self::NOTICE_TYPE_QUESTION => '链接公告',
        self::NOTICE_TYPE_IMAGE      => '详情公告',
    ];

    //公告位置
    const NOTICE_PRESENCE_AREA_FREE  = 0;
    const NOTICE_PRESENCE_AREA_FIRST = 1;
    const NOTICE_PRESENCE_AREA_ORDER = 2;

    const NOTICE_PRESENCE_AREA_MAPPING = [
        self::NOTICE_PRESENCE_AREA_FREE  => '任意页',
        self::NOTICE_PRESENCE_AREA_FIRST => '首页',
        self::NOTICE_PRESENCE_AREA_ORDER => '订货页',
    ];

    /**
     * 根据开始结束时间获得公告状态
     * @return mixed|string
     */
    public function getStatusAttribute()
    {
        if ($this->startTime == $this->endTime) {
            return '调查问卷进行时';
        }
        if ($this->startTime > time()) {
            return self::STATUS_MAPPING[self::STATUS_NOT_STARTED];
        } elseif ($this->startTime < time() && $this->endTime > time()) {
            return self::STATUS_MAPPING[self::STATUS_CONDUCT];
        } else {
            return self::STATUS_MAPPING[self::STATUS_END];
        }
    }

    public function getTypeTextAttribute()
    {
            return self::NOTICE_MAPPING[$this->type] ?? '-';
    }

    public function getPresenceAreaTextAttribute()
    {
        return self::NOTICE_PRESENCE_AREA_MAPPING[$this->presenceArea] ?? '-';
    }


    public function noticeImagesRel()
    {
        return $this->hasMany(SystemNoticeImagesModel::class, 'systemNoticeId', 'id');
    }

    public function noticeCompleteRel()
    {
        return $this->hasMany(SystemNoticeCompleteModel::class, 'systemNoticeId', 'id');
    }
}
